package com.hb.demo.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hb.commons.MsgEnum;
import com.hb.commons.ResponseDto;
import com.hb.config.shiro.JwtToken;
import com.hb.demo.entity.AdminUser;
import com.hb.util.ContextUtil;
import com.hb.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "登陆认证")
@Slf4j
@RestController
public class LoginController {

    @ApiOperation(value = "系统用户登录", notes = "系统用户登录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "password", value = "密码", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/user/login")
    public ResponseDto userLogin(@ApiIgnore @RequestBody AdminUser adminUser) {
        String uname = adminUser.getUname();
        if (StrUtil.isEmpty(uname)) {
            return ResultUtil.msg(MsgEnum.USERNAME_NOT_ALLOW_EMPTY);
        }
        String pword = adminUser.getPword();
        if (StrUtil.isEmpty(pword)) {
            return ResultUtil.msg(MsgEnum.PASSWORD_NOT_ALLOW_EMPTY);
        }

        JwtToken token = new JwtToken(uname, pword);

        ResponseDto resp = ContextUtil.login(token);
        // 无任何返回表示登录成功
        if (resp == null) {
            AdminUser userEntity = token.getUserEntity();
            JSONObject respJSON = JSONUtil.parseObj(userEntity);
            respJSON.set("token", token.getToken());
            return ResultUtil.msg(true, respJSON);
        }
        return resp;
    }
}
